package com.roads.site.service.impl;

import com.roads.common.constant.ResultConstants;
import com.roads.common.constant.UserConstants;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.domain.ExcelResult;
import com.roads.common.utils.DateUtils;
import com.roads.common.utils.StringUtils;
import com.roads.site.domain.SiteLabourBattalion;
import com.roads.site.mapper.SiteLabourBattalionMapper;
import com.roads.site.service.ISiteLabourBattalionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 施工队伍Service业务层处理
 * 
 * @author nhp
 * @date 2022-10-25
 */
@Service
public class SiteLabourBattalionServiceImpl implements ISiteLabourBattalionService {

    @Autowired
    private SiteLabourBattalionMapper mapper;


    /**
     * 根据主键ID查询详情
     * 
     * @param id 施工队伍主键
     * @return 施工队伍
     */
    @Override
    public SiteLabourBattalion getModelById(Integer id) {
        return mapper.getModelById(id);
    }

    /**
     * 查询列表
     * 
     * @param model 施工队伍
     * @return 施工队伍
     */
    @Override
    public List<SiteLabourBattalion> selectModelList(SiteLabourBattalion model) {
        return mapper.selectModelList(model);
    }

    /**
     * 施工队伍下拉框
     *
     * @param institutionCode 标段编号
     * @return 结果
     */
    @Override
    public List<SiteLabourBattalion> dropDownList(String institutionCode) {
        return mapper.dropDownList(institutionCode);
    }

    /**
     * 校验施工队伍名称是否唯一
     *
     * @param model 施工队伍
     * @return 结果
     */
    @Override
    public String checkNameUnique(SiteLabourBattalion model) {
        Integer battalionId = StringUtils.isNull(model.getBattalionId()) ? -1 : model.getBattalionId();
        SiteLabourBattalion info = mapper.checkNameUnique(model.getInstitutionCode(), model.getBattalionName());
        if (StringUtils.isNotNull(info) && !info.getBattalionId().equals(battalionId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 使用数量
     *
     * @param id id
     * @return 数量
     */
    @Override
    public int useCount(Integer id) {
        return mapper.useCount(id);
    }

    /**
     * 新增
     * 
     * @param model 施工队伍
     * @return 结果
     */
    @Override
    public int insert(SiteLabourBattalion model) {
        model.setCreateTime(DateUtils.getNowDate());
        // 设置序号（排序）
        int maxSerialNumber = mapper.getMaxSerialNumber(model.getInstitutionCode());
        maxSerialNumber++;
        model.setOrderNum(maxSerialNumber);
        return mapper.insert(model);
    }

    /**
     * 修改
     * 
     * @param model 施工队伍
     * @return 结果
     */
    @Override
    public int update(SiteLabourBattalion model) {
        model.setUpdateTime(DateUtils.getNowDate());
        return mapper.update(model);
    }

    /**
     * 批量删除
     * 
     * @param ids 主键集合
     * @return 结果
     */
    @Override
    public int deleteByIds(Integer[] ids) {
        return mapper.deleteByIds(ids);
    }

    /**
     * 删除
     * 
     * @param id 施工队伍主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Integer id) {
        return mapper.delete(id);
    }

    /**
     * 施工队伍班组导入
     *
     * @param list 导入数据
     * @param updateSupport 是否覆盖更新
     * @param loginUser 登录用户
     * @param institutionCode 标段编号
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(List<SiteLabourBattalion> list, boolean updateSupport, String loginUser, String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        Date nowDate = DateUtils.getNowDate();
        // excel导入结果集合
        List<ExcelResult> excelResults = new ArrayList<>();
        // 取出该标段下的所有施工队伍
        SiteLabourBattalion battalionSearch = new SiteLabourBattalion();
        battalionSearch.setInstitutionCode(institutionCode);
        // 数据库已经添加的施工队伍
        List<SiteLabourBattalion> dbBattalionList = mapper.selectModelList(battalionSearch);
        // 取出施工队伍最大序列号
        int maxSerialNumber = mapper.getMaxSerialNumber(institutionCode);
        maxSerialNumber++;
        // 即将插入，更新的施工队伍集合
        List<SiteLabourBattalion> insertBattalionList = new ArrayList<>();
        List<SiteLabourBattalion> updateBattalionList = new ArrayList<>();
        // excel起始行
        int index = 2;
        for (SiteLabourBattalion row : list) {
            ExcelResult excelResult = new ExcelResult();
            excelResult.setRow(index);
            row.setInstitutionCode(institutionCode);
            StringBuilder content = new StringBuilder();
            String battalionName = row.getBattalionName();
            if (StringUtils.isEmpty(battalionName)) {
                content.append("队伍名称不能为空;");
                excelResult.setStatus(ResultConstants.RESULT_ERROR);
            }
            // 数据格式有问题，就不用去比对是否存在的逻辑
            if (!ResultConstants.RESULT_ERROR.equals(excelResult.getStatus())) {
                // 查看施工队伍是否存在
                SiteLabourBattalion battalion = checkBattalionIsExist(battalionName, dbBattalionList);
                boolean battalionIsInsert = checkBattalionIsInsert(battalionName, insertBattalionList);
                // 如果数据库存在，并且不进行覆盖更新，则报错
                if (StringUtils.isNotNull(battalion) && !updateSupport) {
                    content.append("队伍名称已存在;");
                    excelResult.setStatus(ResultConstants.RESULT_ERROR);
                } else if (StringUtils.isNotNull(battalion) && updateSupport) {
                    content.append("更新数据库;");
                    excelResult.setStatus(ResultConstants.RESULT_SUCCESS);
                    row.setBattalionId(battalion.getBattalionId());
                    row.setOrderNum(battalion.getOrderNum());
                    row.setCreateBy(battalion.getCreateBy());
                    row.setCreateTime(battalion.getCreateTime());
                    row.setUpdateBy(loginUser);
                    row.setUpdateTime(nowDate);
                    updateBattalionList.add(row);
                } else if (StringUtils.isNull(battalion) && battalionIsInsert) {
                    content.append("重复数据;");
                    excelResult.setStatus(ResultConstants.RESULT_ERROR);
                } else if (StringUtils.isNull(battalion) && !battalionIsInsert) {
                    row.setOrderNum(maxSerialNumber);
                    row.setCreateBy(loginUser);
                    row.setCreateTime(nowDate);
                    excelResult.setStatus(ResultConstants.RESULT_SUCCESS);
                    insertBattalionList.add(row);
                    maxSerialNumber++;
                }
            }
            excelResult.setContent(content.toString());
            index++;
            excelResults.add(excelResult);
        }

        boolean result = true;
        for (ExcelResult excelResult : excelResults) {
            if (ResultConstants.RESULT_ERROR.equals(excelResult.getStatus())) {
                result = false;
                break;
            }
        }
        if (result) {
            // 批量插入和更新
            if (insertBattalionList.size() > 0) {
                mapper.insertBatch(insertBattalionList);
            }
            if (updateBattalionList.size() > 0) {
                mapper.updateBatch(updateBattalionList);
            }
            ajaxResult.put(ResultConstants.RESULT_TAG_MSG, ResultConstants.RESULT_SUCCESS_MESSAGE);
            ajaxResult.put(ResultConstants.RESULT_TAG_STATUS, ResultConstants.RESULT_SUCCESS);
        } else {
            ajaxResult.put(ResultConstants.RESULT_TAG_MSG, ResultConstants.RESULT_ERROR_MESSAGE);
            ajaxResult.put(ResultConstants.RESULT_TAG_STATUS, ResultConstants.RESULT_ERROR);
        }
        ajaxResult.put(ResultConstants.RESULT_TAG_ROWS, excelResults);
        return ajaxResult;
    }

    /**
     * 检查施工队伍名称是否存在
     *
     * @param battalionName 施工队伍名称
     * @param dbBattalionList 数据库里存放的施工队伍
     * @return 结果
     */
    private SiteLabourBattalion checkBattalionIsExist(String battalionName, List<SiteLabourBattalion> dbBattalionList) {
        SiteLabourBattalion battalion = null;
        for (SiteLabourBattalion temp : dbBattalionList) {
            if (battalionName.equals(temp.getBattalionName())) {
                battalion = temp;
                break;
            }
        }
        return battalion;
    }

    /**
     * 检查施工队伍名称是否已经添加至insert集合
     *
     * @param battalionName 施工队伍名称
     * @param insertBattalionList 需要插入的施工队伍
     * @return 结果
     */
    private boolean checkBattalionIsInsert(String battalionName, List<SiteLabourBattalion> insertBattalionList) {
        boolean result = false;
        for (SiteLabourBattalion battalion : insertBattalionList) {
            if (battalionName.equals(battalion.getBattalionName())) {
                result = true;
                break;
            }
        }
        return result;
    }

}
